package twitorg;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.*;

import ecologylab.xml.XMLTranslationException;

import twinb.Conversation;
import twinb.Twinb;
import twinb.text.Search;
import twinb.xml.TwinbData;
import twinb.xml.TwinbList;

public class TwitorgServlet extends HttpServlet
{
    public static Map<String, String> getParams(HttpServletRequest req)
    {
        Map<String, String> params = new HashMap<String, String>();
        Enumeration<String> names = req.getParameterNames();
        while (names.hasMoreElements())
        {
            String name = names.nextElement();
            String value = (String) req.getParameter(name);
            params.put(name, value);
        }
        return params;
    }
    
    public static String asParamString(Map<String, String> params)
    {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String name : params.keySet())
        {
            sb.append(first?"":"&");
            sb.append(name);
            sb.append("=");
            sb.append(params.get(name));
            first = false;
        }
        return sb.toString();
    }
    
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
        // extract parameters
        String uname = (String) req.getSession().getAttribute("username");
        if (uname == null || uname.isEmpty())
            return;
        
        Map<String, String> params = getParams(req);
        if (!params.containsKey("view"))
        {
            params.put("view", "today");
        }
        if (!params.containsKey("page"))
        {
            params.put("page", "0");
        }
        
        String view = params.get("view");
        req.getSession().setAttribute("view", view);
        String page = params.get("page");
        
        int ipage = 0;
        if (page != null)
            ipage = Integer.valueOf(page);
        if (ipage < 0)
            ipage = 0;

        Twinb tw = Twinb.get(uname);
        if (tw.getTweets().size() <= 0)
        {
            tw.setTweets();
            // tw.setPeople();
            tw.setCIM();
            // tw.setConversations();
            tw.rankCVS();
        }

        List<Conversation> cvs = tw.getCvsPage(ipage);
        if (params.containsKey("query"))
        {
            String query = params.get("query");
            Search search = new Search(cvs);
            search.setInput(query);
            search.doSearch();
        }

        resp.setContentType("text/xml");
        resp.getOutputStream().println("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");

        int pp = ipage - 1;
        int np = ipage + 1;
        if (pp < 0)
            pp = 0;
        String site = getPrefix(req);
        params.put("page", String.valueOf((ipage>0)?(ipage-1):ipage));
        String pre = String.format("%s?%s", site, asParamString(params));
        params.put("page", String.valueOf((ipage<tw.getNumberOfCvsPages()-1)?(ipage+1):ipage));
        String next = String.format("%s?%s", site, asParamString(params));
        
        TwinbData td = new TwinbData();
        td.previousPage = pre;
        td.nextPage = next;
        td.view = view;
        td.user = tw.getUser();
        td.twinbList = new TwinbList();
        td.twinbList.conversations = cvs;
        td.twinbList.count = cvs.size();

        String outXml;
        try
        {
            outXml = td.translateToXML().toString();
            resp.getOutputStream().println(outXml);
        }
        catch (XMLTranslationException e)
        {
            resp.getOutputStream().println("xml translation error: " + e.getMessage());
        }
    }

    private String getPrefix(HttpServletRequest req)
    {
        // TODO Auto-generated method stub
        String scheme = req.getScheme();
        String serverName = req.getServerName();
        String port = String.valueOf(req.getServerPort());
        String uri = req.getRequestURI();
        
        String s1 = scheme + "://" + serverName;
        if (!port.equals("80"))
            s1 += ":" + port;
        
        return s1 + uri;
    }
}
